package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagementApi;
import com.xuecheng.api.content.model.file.UploadTokenResult;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RefreshScope
@RestController
public class FileManagerController implements FileManagementApi {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.token.type}")
    private String tokenType;
    @Value("${file.token.deadline}")
    private int deadline;

    @GetMapping("common/qnUploadToken")
    public UploadTokenResult generateUploadToken() {
        HashMap<String, Object> requestBody = new HashMap<>();
        requestBody.put("tokenType", tokenType);
        requestBody.put("scope", bucket);
        requestBody.put("deadline", deadline);
        // 生成文件的key, 保证唯一性
        String fileKey = UUID.randomUUID().toString() + RandomStringUtils.randomAlphanumeric(16);
        requestBody.put("key", fileKey);

        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, requestBody, Map.class);

        int statusCode = responseEntity.getStatusCodeValue();
        if (!(HttpStatus.OK.value() == statusCode)) {
            ExceptionCast.cast(ContentErrorCode.E_120024);
        }

        Map body = responseEntity.getBody();
        Object obj = body.get("code");
        int code = CommonErrorCode.SUCCESS.getCode();
        if (!(code == (int) obj)) {
            ExceptionCast.cast(ContentErrorCode.E_120025);
        }

        UploadTokenResult tokenResult = new UploadTokenResult();
        tokenResult.setQnToken(body.get("result").toString());
        tokenResult.setScope(bucket);
        tokenResult.setKey(fileKey);
        tokenResult.setTokenType(tokenType);
        tokenResult.setUp_region(region);
        tokenResult.setDomain(domain);
        tokenResult.setDeadline(deadline);

        return tokenResult;
    }
}
